package live.betterman.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import live.betterman.system.model.SysMenu;
import live.betterman.system.dao.SysMenuMapper;
import live.betterman.system.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhudawei
 * @since 2024-11-04
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public List<SysMenu> tree() {
        List<SysMenu> data = list(Wrappers.lambdaQuery(SysMenu.class).orderByAsc(SysMenu::getSort));
        return getChildren(data, null);
    }

    private List<SysMenu> getChildren(List<SysMenu> data, String parentId) {
        List<SysMenu> tree = data.stream().filter(item -> parentId == null
                        ? "".equals(item.getParentId()) : parentId.equals(item.getParentId()))
                .collect(Collectors.toList());
        return tree.stream().peek(item -> item.setChildren(getChildren(data, item.getMenuId())))
                .collect(Collectors.toList());
    }

    @Override
    public List<SysMenu> getUserMenus(String userId) {
        // 获取用户的所有菜单
        List<SysMenu> menus = baseMapper.selectMenusByUserId(userId);
        
        // 构建树形结构
        return buildMenuTree(menus);
    }
    
    private List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        Map<String, List<SysMenu>> menuMap = menus.stream()
                .collect(Collectors.groupingBy(SysMenu::getParentId));
                
        menus.forEach(menu -> menu.setChildren(menuMap.getOrDefault(menu.getMenuId(), new ArrayList<>())));
        
        return menus.stream()
                .filter(menu -> menu.getParentId() == null || menu.getParentId().isEmpty())
                .collect(Collectors.toList());
    }
}
